package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.RedisData;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCache;
import com.hmdp.utils.RedisClient;
import com.hmdp.utils.SystemConstants;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisClient redisClient;

    @Autowired
    RedisCache redisCache;

    @Autowired
    RBloomFilter<Long> bloomFilter;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //解决缓存穿透
    /*@Override
    public Result queryShopById(Long id) {
        String key=SHOP_DETAIL+id;
        //命中返回"",未命中返回null
        String shopString = stringRedisTemplate.opsForValue().get(key);//未命中则会有""与null两种情况
        //在redis中查询商铺信息,存在，直接返回
        if (StrUtil.isNotEmpty(shopString)){
            Shop shop = JSONUtil.toBean(shopString, Shop.class);
            return Result.ok(shop);
        }
        //未命中
        //是空的则shopString为空字符串，或者是null
        if (shopString !=null){
            return Result.fail("不存在当前商铺");
        }
        //不存在，去数据库查询用户信息
        Shop shop = getById(id);
        if (Objects.isNull(shop)) {
            //不存在，则将空字符串保存在Redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return Result.fail("不存在此商铺!");
        }
        //存在，将数据返回保存在Redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回用户信息
        return Result.ok(shop);
    }*/
    @Override
    public Result queryShopById(Long id) {
        if (bloomFilter.contains(id)){
            //查询redis中是否有数据
            String json = stringRedisTemplate.opsForValue().get(SHOP_DETAIL + id);
            if (StrUtil.isNotEmpty(json)){
                Shop shop = JSONUtil.toBean(json, Shop.class);
                return Result.ok(shop);
            }else {
                //未命中访问数据库（并将数据保存在redis）
                Shop shop = getById(id);
                if (Objects.isNull(shop)) {
                    //不存在，则将空字符串保存在Redis
                    stringRedisTemplate.opsForValue().set(SHOP_DETAIL + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                    return Result.fail("不存在此商铺!(数据库回应)");
                }else {
                    //存在，将数据返回保存在Redis
                    stringRedisTemplate.opsForValue().set(SHOP_DETAIL + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
                    return Result.ok(shop);
                }
            }
        }else {
            return Result.fail("不存在此商铺!(bloom过滤)");
        }

    }
    //解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = SHOP_DETAIL + id;
        String lockKey = LOCK_SHOP + id;
        Shop shop = null;
        try {
            //命中返回"",未命中返回null
            String shopString = stringRedisTemplate.opsForValue().get(key);//未命中则会有""与null两种情况
            //在redis中查询商铺信息,存在，直接返回
            if (StrUtil.isNotEmpty(shopString)) {
                shop = JSONUtil.toBean(shopString, Shop.class);
                return shop;
            }
            //未命中
            //是空的则shopString为空字符串，或者是null
            if (shopString != null) {
                return null;
            }
            //获取锁，否则休眠等待
            if (!tryLock(lockKey)) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //不存在，去数据库查询用户信息
            shop = getById(id);
            if (Objects.isNull(shop)) {
                //不存在，则将空字符串保存在Redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在，将数据返回保存在Redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//            redisCache.setCacheObject(key,shop,30,TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            unLock(lockKey);
        }
        //返回用户信息
        return shop;
    }

    //这里默认数据已经存入Redis，提前做好这一步操作
    public Shop queryWithLogicalExpire(Long id) {
        String key = SHOP_DETAIL + id;
        String lockKey = LOCK_SHOP + id;
        //命中返回"",未命中返回null
        String shopString = stringRedisTemplate.opsForValue().get(key);
        //在redis中查询商铺信息,不存在直接返回空
        if (StrUtil.isEmpty(shopString)) {
            return null;
        }
        //序列化成RedisData对象,并获取shop
        RedisData redisData = JSONUtil.toBean(shopString, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getRedisData(), Shop.class);
        //不为空，判断是否已经失效
        //未失效
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            return shop;
        }
        //失效,获取锁，开辟新线程去执行查数据库的操作,执行缓存重建
        if (tryLock(lockKey)) {
            //线程池
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                        try {
                            saveShop2Redis(id, 1800L);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            unLock(lockKey);
                        }
                    }
            );
        }
        //返回用户信息
        return shop;
    }

    private boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id, Long expireSeconds) {
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setRedisData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(SHOP_DETAIL + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result updateShopById(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("对应ID商铺不存在");
        }
        //保存数据于数据库中
        updateById(shop);
        //删除Redis对应缓存
        stringRedisTemplate.delete(SHOP_DETAIL + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if (x == null || y ==null){
            Page<Shop> page = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //设置查询参数
        int from = (current - 1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        String key = "shop:geo:" + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> radiusShop =
                stringRedisTemplate.opsForGeo().radius(key, new Circle(new Point(x, y),
                                new Distance(5D, Metrics.KILOMETERS)),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));
        /*GeoResults<RedisGeoCommands.GeoLocation<String>> radiusShop = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));*/
        if (radiusShop == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = radiusShop.getContent();
        if (content.size() <= from) {
            return Result.ok(Collections.emptyList());
        }
        Map<Long,Double> map = new HashMap<>(content.size());//map含有id和distance两个参数，distance用来排序
        List<Long> ids = new ArrayList<>();
        /*for (GeoResult<RedisGeoCommands.GeoLocation<String>> location : content) {
            double distance = location.getDistance().getValue();
            Long shopId = Long.valueOf(location.getContent().getName());
            ids.add(shopId);
            map.put(shopId,distance);
        }*/
        content.stream().skip(from).forEach(location ->{
                    double distance = location.getDistance().getValue();
                    Long shopId = Long.valueOf(location.getContent().getName());
                    ids.add(shopId);
                    map.put(shopId,distance);
                }
        );
        if (ids == null && ids.size() == 1){
            return Result.ok(Collections.emptyList());
        }
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list();
        for (Shop shop : shops) {
            Long id = shop.getId();
            shop.setDistance(map.get(id));
        }
        return Result.ok(shops);
    }

    @Override
    public Result queryShopExcel(HttpServletResponse response){
        List<Shop> list = list();
//        InputStream in = this.getClass().getClassLoader().getResourceAsStream("/template/shopList.xlsx");
        try {
            FileInputStream in = new FileInputStream("D:\\桌面\\Code\\dianping\\hm-dianping\\src\\main\\resources\\template\\shopList.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            for (int i=1;i<=list.size();i++){
                sheet.getRow(i).getCell(0).setCellValue(list.get(i-1).getName());
                sheet.getRow(i).getCell(1).setCellValue(list.get(i-1).getAddress());
                sheet.getRow(i).getCell(2).setCellValue(list.get(i-1).getAvgPrice());
                sheet.getRow(i).getCell(3).setCellValue(list.get(i-1).getScore());
                sheet.getRow(i).getCell(4).setCellValue(list.get(i-1).getOpenHours());
            }
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.ok();
    }
}





